import { LogHelper } from "../../utils/logHelper";

export class OuterOreCarryTask implements ICreepTask {
  public run(creep: Creep): void {
    const range = 5; //指定范围内
    const bornRoom = Game.rooms[creep.memory.bornRoom];
    const relayRole = "outerOre_carry_relay";

    if(creep.store.getFreeCapacity(RESOURCE_ENERGY) === 0){
      // 判断是否有接力的creep 如果有转移资源给接力的Creep
      let creepRelay:Creep | null = null;
      if(creep.memory.relayTarget){
        creepRelay = Game.getObjectById(creep.memory.relayTarget);
        if(!creepRelay){
          creep.memory.spawnApplyFor = false;
          delete creep.memory.relayTarget;
        }
      }
      if(!creepRelay){
        // 把资源搬运到storage或spawn附近
        const storage = Game.rooms[creep.memory.bornRoom].storage;
        if(storage){
          if (creep.transfer(storage, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
            creep.go(storage);
          } 
        }
        else{
          const spawn = bornRoom.spawn();
          if(spawn){
            if(creep.pos.getRangeTo(spawn) > range){
              creep.go(spawn);
            }
            else{
              creep.drop(RESOURCE_ENERGY)
              if(creep.store.getUsedCapacity(RESOURCE_ENERGY) === 0){
                creep.memory.working = true;
              }
            }
          }
        }
        // 申请一个 creepRelay 
        if(!creep.memory.spawnApplyFor){
          const relayCreeps = Object.values(Game.creeps).filter((creep) => 
            creep.memory.role === relayRole && creep.memory.relayTarget && creep.memory.relayTarget === creep.id);
          const queueCreeps = bornRoom.spawnQueueGetRole(relayRole,(c)=> c.memory.relayTarget !== undefined && c.memory.relayTarget === creep.id);
          // 空闲的relay 
          const relayLeisureCreeps = Object.values(Game.creeps).filter((creep) => 
            creep.memory.role === relayRole && (!creep.memory.relayTarget || creep.memory.relayTarget === undefined));

          if(relayCreeps.length === 0 && queueCreeps.length === 0 && relayLeisureCreeps.length === 0){
            let body = bornRoom.calculateCreepBody({
              [MOVE]:0.5,
              [CARRY]:0.5,
            },800);
            bornRoom.spawnQueueAdd(relayRole,body,{ role:relayRole, bornRoom:bornRoom.name,relayTarget:creep.id });
            LogHelper.log(`外矿房间管理[${creep.memory.source?.pos.roomName}] Creep ${creep.name} 申请孵化 ${relayRole}`);
            creep.memory.spawnApplyFor = true;
          }
          else if(relayLeisureCreeps.length > 0){
            // 把空闲的接力者分配任务
            const leisureCreeps = relayLeisureCreeps[0];
            leisureCreeps.memory.relayTarget = creep.id;
            creep.memory.relayTarget = leisureCreeps.id;
          }
        }
      }
      else {
        if (creep.transfer(creepRelay, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
          creep.go(creepRelay);
        } 
      }
    }
    else{
      if(creep.memory.source){
        creep.memory.working = true;
        const source = Game.getObjectById(creep.memory.source.id);
        if(source){
          if(creep.pos.getRangeTo(source) > range){
            creep.go(source);
          } 
          else {
            /**
             * 指定范围内掉落的资源
             */
            const resources = source.pos.findInRange(FIND_DROPPED_RESOURCES, range);
            for(const fallsource of resources){
              if(creep.pickup(fallsource) === ERR_NOT_IN_RANGE){
                creep.go(fallsource);
              }
            }
          }
        }
      }
    }

    // 如果为外矿的采集 自动申请
    if(creep.ticksToLive && creep.ticksToLive <= 30){
      if(creep.memory.source && !creep.memory.spawnApplyFor){
        const room = Game.rooms[creep.memory.bornRoom];
        const role = 'outerOreCarry';
        const body = room.calculateCreepBody({
          [MOVE]:0.5,
          [CARRY]:0.5,
        },800);
        room.spawnQueueAdd(role,body,{ role, bornRoom:room.name,  source: { id:creep.memory.source.id,pos:creep.memory.source.pos }});
        creep.memory.spawnApplyFor = true;
        LogHelper.log(`外矿采集 Creep [${creep.name}] 申请孵化 ${role}`);
      }
    }
  }
}